const DB = wx.cloud.database()
var util = require('../../utils/util.js');
var cbc = require('../../utils/cbc.js');
var recorder = wx.getRecorderManager();
var innerAudioContext = wx.createInnerAudioContext() //获取播放对象
var qunId, that, itemSrc;
let key = '123456';
let is_fff = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    focus:false,
  },
  renwu(e){
    wx.showToast({
      title: '待确认地址',
      icon:'none'
    })
  },
  onShow() {
    console.log('-----上线线')
    let info = wx.getStorageSync('chat_item')
    DB.collection('friends')
      .where({
        _id: info._id
      }).get().then(res => {
        console.log('-----', res)
        if (res.data[0].a == wx.getStorageSync('userInfo')._openid) {
          console.log('-----a上线', res.data[0].a, wx.getStorageSync('userInfo')._openid)
          DB.collection('friends').doc(info._id).update({
            data: {
              a_zaixian: true,
              a_hongdian:false
            }
          })
        } else {
          console.log('-----b上线', res.data[0].b, wx.getStorageSync('userInfo')._openid)
          DB.collection('friends').doc(info._id).update({
            data: {
              b_zaixian: true,
              b_hongdian:false
            }
          })
        }
      })
  },
  focusbg(){
    is_fff=true
    this.setData({
      focus:false
    })
  },
  bindblur(){
    if(is_fff)return
    this.setData({
      focus:true
    })
  },
  focusss(){
    is_fff=false
    this.setData({
      focus:true
    })
  },
  onUnload() {
    console.log('-----离线')

    let info = wx.getStorageSync('chat_item')
    DB.collection('friends')
      .where({
        _id: info._id
      }).get().then(res => {
        if (res.data[0].a == wx.getStorageSync('userInfo')._openid) {
          console.log('-----a离线')
          DB.collection('friends').doc(info._id).update({
            data: {
              a_zaixian: false
            }
          })
        } else {
          console.log('-----b离线')
          DB.collection('friends').doc(info._id).update({
            data: {
              b_zaixian: false
            }
          })
        }
      })
  },
  // 发送消息
  sendOut(e) {
    let that = this
    getApp().sendMsg()
    console.log(1111, e)
    if (this.data.txt == '') {
      console.log(222)
      wx.showToast({
        title: '请输入聊天内容',
        icon: 'none',
      })
    } else {
      console.log(333)
      var a_hongdian =false;
      var b_hongdian =false;
      if(this.data.my_type=="a"&&this.data.chatObj.b_zaixian==false){
        b_hongdian = true
      }
      if(this.data.my_type=="b"&&this.data.chatObj.a_zaixian==false){
        a_hongdian = true
      }
      var msgList = this.data.list;
      var item = {
        openid: this.data.openid,
        txt: this.data.txt,
        img: this.data.my_img,
        name: this.data.my_name,
      }
      msgList.push(item)
      console.log(444, msgList)
      DB.collection('friends').doc(this.data.info._id).update({
        data: {
          a_hongdian:a_hongdian,
          b_hongdian:b_hongdian,
          msgList: msgList
        },
        success(res) {
          console.log(555, msgList)
          that.setData({
            txt:""
          })
          let openid, senMsgTo;
          if (that.data.openid == that.data.info.a) {
            openid = that.data.info.b;
            // 发送模板消息给B，判断B在线状态
            if (that.data.chatObj.b_zaixian) {
              return
            }
          } else {
            openid = that.data.info.a;
            // 发送模板消息给B，判断A在线状态
            if (that.data.chatObj.a_zaixian) {
              return
            }
          }
          var data = {
            openid: openid,
            page: "pages/friends_list/friends_list?openid=" + wx.getStorageSync('userInfo')._openid,
            time3: util.formatTime(new Date()),
            thing1: wx.getStorageSync('userInfo').userInfoDetail.nicheng,
            thing2: "收到新的聊天信息，请查看",
            templateId: "eDqGleQrM6Q9OL1d54CknCpSwG1_9w5z-Pn_fj6rng0",
            miniprogramState: "developer"
          }
          console.log(666, msgList)
          console.log('发送成功-------------', data)
          // developer为开发版；trial为体验版；formal为正式版；默认为正式版
          wx.cloud.callFunction({
            name: "sendMsg",
            data: data,
            success(res) {
              console.log('组队申请通知chengg-------------', res.result)
            },
            fail(err) {
              console.log('组队申请通知失败-------------', err)

            }
          })
          console.log('消息发送', res)
          that.setData({
            txt: ''
          })

        },
        fail(res) {
          console.log('登录失败', res)
        }
      })
    }
  },

  onLoad: function (options) {
    let info = wx.getStorageSync('chat_item')
    wx.setNavigationBarTitle({
      title: info.a_name + '和' + info.b_name + '的聊天',
    })
    this.setData({
      info: info,
      openid: wx.getStorageSync('userInfo')._openid,
      my_img: wx.getStorageSync('userInfo').userInfoDetail.hande,
      my_name: wx.getStorageSync('userInfo').userInfoDetail.nicheng,
    })
    that = this
    this.onMsg2();
    // qunId = options.qunId
    // console.log('群ID', options)

    // that.userFun()
    // that.prohibit()

  },

  // 获取聊天信息
  onMsg2() {
    const _ = DB.command;
    var _id = that.data.info._id
    console.log("that.data.info._id", _id)

    DB.collection('friends')
      .where({
        _id: _id
      })
      .watch({
        onChange: function (snapshot) {
          var listArr = snapshot.docs;
          console.log('---', listArr)
          // listArr.forEach((item, idx) => {
          //   console.log('---', item._openid)
          // })
          that.setData({
            chatObj: listArr[0],
            list: listArr[0].msgList,
            my_type: listArr[0].a == that.data.openid ? "a" : "b"
          })
          
          setTimeout(() => {
            that.bottom()
          }, 500)
        },
        onError: function (err) {
          console.error('----------------error', err)
        }
      })
  },
  jiemi() {
    this.setData({
      jiemi: true,

    })
    this.onLoad(qunId)
  },

  showCancelOrder: function () {
    this.setData({
      showModal: true
    })
  },
  modal_click_Hidden: function () {
    this.setData({
      showModal: false,
    })
  },
  // 确定
  Sure: function () {
    console.log(this.data.key)
    if (this.data.key != key) {
      wx.showToast({
        title: '请填写正确的解密秘钥',
        icon: 'none'
      })
      return
    } else {
      this.modal_click_Hidden()
      this.jiemi();
    }
  },
  changeCancelReason: function (e) {
    this.setData({
      key: e.detail.value
    })
  },
  previewImage: function (e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      urls: [current]
    })
  },
  // 点击录音开始播放事件
  my_audio_click: function (e) {
    itemSrc = e.currentTarget.dataset.src;
    console.log('url地址', itemSrc);
    innerAudioContext.src = itemSrc;
    innerAudioContext.seek(0);
    innerAudioContext.play();
    // wx.playVoice({
    //   filePath: src,
    //   complete(com) {
    //     console.log(com)
    //    }
    // })
  },
  // 首页
  goHome() {
    wx.switchTab({
      url: '../group/group'
    })

  },

  // 群成员
  number() {
    let userList = JSON.stringify(this.data.userList)
    wx.navigateTo({
      url: '../member/member?qunId=' + qunId,
    })
  },
  bottom: function () {
    var that = this;
    this.setData({
      scrollTop: 100000
    })
  },
  // 动态监听禁言状态
  prohibit() {
    return
    console.log('8888888888888', qunId)
    const watcher = DB.collection('qunList')
      .where({
        _id: qunId
      })
      .watch({
        onChange: function (res) {

          let arr = res.docs[0]
          if (res.docs.length > 0) {
            console.log('动态监听禁言状态', arr._openId + ':' + wx.getStorageSync('openId'))
            let opid = arr._openId
            if (arr.prohibit == '1') {
              if (arr._openId == wx.getStorageSync('openId')) {
                that.setData({
                  prohibit: '0'
                })
              } else {
                that.setData({
                  prohibit: '1'
                })
              }
            } else {
              const watcher = DB.collection('qunUserList')
                .where({
                  qunId: qunId,
                  _openId: wx.getStorageSync('openId')
                })
                .watch({
                  onChange: function (res) {

                    let arrr = res.docs[0]
                    console.log('动态监听禁言状态', arrr._openId + ':' + wx.getStorageSync('openId'))
                    if (arrr.prohibit == '1') {
                      if (arrr._openId == opid) {
                        that.setData({
                          prohibit: '0'
                        })
                      } else {
                        that.setData({
                          prohibit: '1'
                        })
                      }
                    } else {
                      that.setData({
                        prohibit: '0'
                      })
                    }


                  },
                  onError: function (err) {
                    // console.error('----------------error', err)
                  }
                })
            }
          }

        },
        onError: function (err) {
          // console.error('----------------error', err)
        }
      })
  },

  // 禁言提示
  prohibitTis() {
    wx.showToast({
      title: '禁言中......',
      icon: 'none'
    })
  },
  // 获取群成员
  userFun() {
    DB.collection('qunUserList').where({
        qunId: qunId
      })
      .get({
        success: function (res) {
          console.log(666666666, res)
          that.setData({
            userNumber: res.data.length,
            userList: res.data
          })

        }
      })
  },

  // 群公告
  notice() {
    wx.showModal({
      title: '群公告',
      content: this.data.userList[0].qunTitle,
      showCancel: false,
      success(res) {
        if (res.confirm) {
          // console.log('用户点击确定')
        }
      }
    })
  },
  input(e) {
    this.setData({
      txt: e.detail.value
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 手指点击录音
  // voice_ing_start: function () {
  //   console.log('手指点击录音')
  //   wx.showToast({
  //     title: '按住录音，松开发送',
  //     icon: 'none'
  //   })
  //   this.setData({
  //     voice_ing_start_date: new Date().getTime(), //记录开始点击的时间
  //   })
  //   const options = {
  //     duration: 10000, //指定录音的时长，单位 ms
  //     sampleRate: 8000, //采样率
  //     numberOfChannels: 1, //录音通道数
  //     encodeBitRate: 24000, //编码码率
  //     format: 'mp3', //音频格式，有效值 aac/mp3
  //     audioSource: 'auto',
  //     frameSize: 12, //指定帧大小，单位 KB
  //   }
  //   recorder.start(options) //开始录音

  //   this.animation = wx.createAnimation({
  //     duration: 1200,
  //   }) //播放按钮动画
  //   that.animation.scale(0.8, 0.8); //还原
  //   that.setData({

  //     spreakingAnimation: that.animation.export()
  //   })
  // },
  onReady: function () {
    // this.on_recorder();
    innerAudioContext.offError((err) => {
      console.log('监听播放音频失败', err)
    })
    innerAudioContext.onError((err) => {
      console.log('监听音频播放错误事件', err)
      if (err.errCode == '10001') {
        setTimeout(() => {
          innerAudioContext.autoplay = true;

          innerAudioContext.src = itemSrc;

          // innerAudioContext.src = itemSrc;
          // innerAudioContext.seek(0);
          // innerAudioContext.play();
        }, 100)
      }

    })
  },

  // 发送图片
  upLoad() {
    getApp().sendMsg();
    wx.chooseImage({
      success: chooseResult => {
        console.log('chooseResult.tempFilePaths[0]',chooseResult.tempFilePaths[0])
        wx.cloud.uploadFile({
          cloudPath: '11aachatImg/'+new Date().getTime(),
          filePath: chooseResult.tempFilePaths[0],
          success: res => {
            console.log('上传成功', res)
            let imgUrl = res.fileID
            that.fileUpMsg(imgUrl,2)
          },
          fail:err=>{
            console.log('失败',err)
          }
        })
      },
    })
  },
  fileUpMsg(fileUrl,type){
    var a_hongdian =false;
      var b_hongdian =false;
      if(this.data.my_type=="a"&&this.data.chatObj.b_zaixian==false){
        b_hongdian = true
      }
      if(this.data.my_type=="b"&&this.data.chatObj.a_zaixian==false){
        a_hongdian = true
      }
      var msgList = this.data.list;
      var item = {
        openid: this.data.openid,
        chat_img: fileUrl,
        img: this.data.my_img,
        name: this.data.my_name,
      }
      msgList.push(item)
      console.log(444, msgList)
      DB.collection('friends').doc(this.data.info._id).update({
        data: {
          a_hongdian:a_hongdian,
          b_hongdian:b_hongdian,
          msgList: msgList
        },
        success(res) {
          console.log(555, msgList)
          that.setData({
            txt:""
          })
          let openid, senMsgTo;
          if (that.data.openid == that.data.info.a) {
            openid = that.data.info.b;
            // 发送模板消息给B，判断B在线状态
            if (that.data.chatObj.b_zaixian) {
              return
            }
          } else {
            openid = that.data.info.a;
            // 发送模板消息给B，判断A在线状态
            if (that.data.chatObj.a_zaixian) {
              return
            }
          }
          var data = {
            openid: openid,
            page: "pages/friends_list/friends_list?openid=" + wx.getStorageSync('userInfo')._openid,
            time3: util.formatTime(new Date()),
            thing1: wx.getStorageSync('userInfo').userInfoDetail.nicheng,
            thing2: "收到新的聊天信息，请查看",
            templateId: "eDqGleQrM6Q9OL1d54CknCpSwG1_9w5z-Pn_fj6rng0",
            miniprogramState: "developer"
          }
          console.log(666, msgList)
          console.log('发送成功-------------', data)
          // developer为开发版；trial为体验版；formal为正式版；默认为正式版
          wx.cloud.callFunction({
            name: "sendMsg",
            data: data,
            success(res) {
              console.log('组队申请通知chengg-------------', res.result)
            },
            fail(err) {
              console.log('组队申请通知失败-------------', err)

            }
          })
          console.log('图片发送', res)

        },
        fail(res) {
          console.log('登录失败', res)
        }
      })
  },
  // 录音监听事件
  // on_recorder: function () {
  //   console.log('录音监听事件');
  //   recorder.onStart((res) => {
  //     console.log('开始录音');
  //   })
  //   recorder.onStop((res) => {
  //     let {
  //       tempFilePath
  //     } = res;
  //     console.log('停止录音,临时路径', tempFilePath);
  //     var x = new Date().getTime() - this.data.voice_ing_start_date
  //     if (x > 1000) {
  //       let timestamp = new Date().getTime();
  //       wx.cloud.uploadFile({
  //         cloudPath: "sounds/" + timestamp + '.mp3',
  //         filePath: tempFilePath,
  //         success: res => {
  //           console.log('上传成功', res)
  //           that.setData({
  //             soundUrl: res.fileID,
  //           })

  //           var data = {
  //             _qunId: qunId,
  //             _openId: wx.getStorageSync('openId'),
  //             // 消息
  //             text: '',
  //             voice: res.fileID,
  //             img: '',
  //             // 时间
  //             dataTime: util.nowTime(),
  //             // 头像
  //             sendOutHand: wx.getStorageSync('userInfo').avatarUrl,
  //             // 昵称
  //             sendOutname: wx.getStorageSync('userInfo').nickName
  //           }
  //           console.log(data)
  //           wx.cloud.callFunction({
  //             name: "news",
  //             data: data,
  //             success(res) {
  //               console.log('发送语音发送', res)
  //             },
  //             fail(res) {
  //               console.log('发送语音失败', res)
  //             }
  //           })
  //         },
  //       })
  //     }
  //   })
  //   recorder.onFrameRecorded((res) => {
  //     return
  //     console.log('onFrameRecorded  res.frameBuffer', res.frameBuffer);
  //     string_base64 = wx.arrayBufferToBase64(res.frameBuffer)

  //     console.log('string_base64--', string_base64)
  //   })
  // },
  // // 手指松开录音
  // voice_ing_end: function () {
  //   console.log('手指松开录音')

  //   that.setData({
  //     voice_icon_click: false,
  //     animationData: {}
  //   })
  //   this.animation = "";
  //   var x = new Date().getTime() - this.data.voice_ing_start_date
  //   if (x < 1000) {
  //     console.log('录音停止，说话小于1秒！')
  //     wx.showModal({
  //       title: '提示',
  //       content: '说话要大于1秒！',
  //     })
  //     recorder.stop();
  //   } else {
  //     // 录音停止，开始上传
  //     recorder.stop();
  //   }
  // },
  // 点击语音图片
  // voice_icon_click: function () {
  //   this.setData({
  //     voice_icon_click: !this.data.voice_icon_click
  //   })
  // },
})